/**
 * @Title: CustomerCardServiceImpl.java
 * @Description: TODO(用一句话描述该文件做什么)
 * @author 张鑫
 * @phone 17561783855
 * @date 2019年5月20日
 */
package com.fortune.rainshinesystem.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.fortune.rainshinecommon.base.MsgModel;
import com.fortune.rainshinecommon.base.ParmsModel;
import com.fortune.rainshinecommon.enums.ResultCode;
import com.fortune.rainshinecommon.model.CustomerModel;
import com.fortune.rainshinecommon.model.system.CardModel;
import com.fortune.rainshinecommon.model.system.CustomerCardModel;
import com.fortune.rainshinecommon.model.system.CustomerServiceTotalModel;
import com.fortune.rainshinesystem.mapper.CardMapper;
import com.fortune.rainshinesystem.mapper.CustomerCardMapper;
import com.fortune.rainshinesystem.mapper.CustomerMapper;
import com.fortune.rainshinesystem.mapper.CustomerServiceTotalMapper;
import com.fortune.rainshinesystem.service.CustomerCardService;
import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.Wrapper;

import java.util.*;

/**
 * @ClassName: CustomerCardServiceImpl
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author 张鑫
 * @phone 17561783855
 * @date 2019年5月20日
 *
 */
@Service
public class CustomerCardServiceImpl implements CustomerCardService {
    private static final Logger logger = LoggerFactory.getLogger(CustomerCardServiceImpl.class);

    @Autowired
    private CustomerCardMapper mapper;
    @Autowired
    private CardMapper cardMapper;
    @Autowired
    private CustomerServiceTotalMapper serviceTotalMapper;
    @Autowired
    private CustomerMapper customerMapper;

    @Override
    @Transactional
    public MsgModel add(CustomerCardModel model) {
        try {

            //会员卡编码
           String uuid = UUID.randomUUID().toString().replaceAll("-", "");

            //根据会员卡code获取会员卡信息
            CardModel card = cardMapper.selectById(model.getCardId());

            model.setCardCode(uuid);
            model.setCardName(card.getCardName());
            model.setCardTimes(card.getServiceTimes());
            model.setServiceTimes(card.getServiceTimes());
            model.setCustomerCode(model.getCustomerCode());
            model.setCreateId(model.getUser().getUserId());
            model.setUpdateId(model.getUser().getUserId());

            int res = mapper.insert(model);
            if (res > 0) {
                //获取用户会员卡总表信息
                CustomerServiceTotalModel parm = new CustomerServiceTotalModel();
                parm.setCardId(model.getCardId());
                parm.setShopId(model.getShopId());
                parm.setCustomerId(model.getCustomerId());
                CustomerServiceTotalModel total = serviceTotalMapper.selectOne(parm);
                //判断若不为空则更新总次数
                if (total != null) {
                    total.setServiceTimes(total.getServiceTimes() + model.getCardTimes());
                    serviceTotalMapper.updateAllColumnById(total);
                } else {
                    parm.setServiceTimes(model.getCardTimes());
                    parm.setCreateId(model.getUser().getUserId());
                    parm.setUpdateId(model.getUser().getUserId());
                    serviceTotalMapper.insert(parm);
                }
                return new MsgModel("购买会员卡成功！", ResultCode.SUCCESS);
            } else {
                return new MsgModel("购买会员卡失败！", ResultCode.FAILURE);
            }
        } catch (Exception e) {
            logger.error("CustomerCardServiceImpl add ====> {}", e);
            return new MsgModel("购买会员卡失败！", ResultCode.FAILURE);
        }
    }

    @Override
    public MsgModel update(CustomerCardModel model) {
        try {
            model.setUpdateId(model.getUser().getUserId());
            int res = mapper.updateAllColumnById(model);
            if (res > 0) {
                return new MsgModel("更新成功！", ResultCode.SUCCESS);
            } else {
                return new MsgModel("更新失败！", ResultCode.FAILURE);
            }
        } catch (Exception e) {
            logger.error("CustomerCardServiceImpl update ====> {}", e);
            return new MsgModel("更新失败！", ResultCode.FAILURE);
        }
    }

    @Override
    public MsgModel list(ParmsModel parm) {
        try {
            Page<CustomerCardModel> page = new Page<>(parm.getPage(), parm.getLimit());
            List<CustomerCardModel> list = Optional.ofNullable(mapper.getAllRecords(parm, page)).orElse(Lists.newArrayList());
            if(!list.isEmpty()){
                list.forEach(e->{
//                    CardModel cardModel = new CardModel();
//                    cardModel.setCardCode(e.getCardCode());
//                    cardModel.setIsActive((short) 1);
                    CardModel c = cardMapper.selectById(e.getCardId());
                    e.setCardId(c.getId());
                });
            }
            page.setRecords(list);
            int total = mapper.getAllRecordsCount(parm);
            return new MsgModel(total, page.getRecords());
        } catch (Exception e) {
            logger.error("CustomerCardServiceImpl list ====> {}", e);
            return new MsgModel(ResultCode.FAILURE);
        }
    }

    @Override
    public MsgModel delete(CustomerCardModel model) {
        try {
            boolean rs = mapper.deleteById(model.getId()) > 0;
            if (rs) {
                return new MsgModel("删除成功！", ResultCode.SUCCESS);
            } else {
                return new MsgModel("删除失败！", ResultCode.FAILURE);
            }
        } catch (Exception e) {
            logger.error("CustomerCardServiceImpl delete ====> {}", e);
            return new MsgModel("删除失败！", ResultCode.FAILURE);
        }
    }

    @Override
    public List<CustomerServiceTotalModel> getListByCustomerId(Integer customerId) {
        Wrapper<CustomerServiceTotalModel> wrapper = new EntityWrapper<>();
        wrapper.eq("customer_id", customerId);
        List<CustomerServiceTotalModel> list = Optional.ofNullable(serviceTotalMapper.selectList(wrapper)).orElse(Lists.newArrayList());
        if(!list.isEmpty()){
            CustomerModel customerModel = customerMapper.selectById(customerId);
            list.forEach(e->{
                e.setCustomerName(customerModel.getCustomerName());
                e.setCustomerPhone(customerModel.getCustomerPhone());
                CardModel cardModel = cardMapper.selectById(e.getCardId());
                e.setCardName(cardModel.getCardName());
            });
        }
        return list;
    }


}
